package com.lead.security.encryption.SM4;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.security.Provider;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @ClassName: SM4Util
 * @Description:
 * @Author: zhouzhiguo
 * @Date: 2025/5/13 15:05
 * @Version: 5.3.8
 */

public class SM4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    /**
     * 加密 SM4
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptECB(String data, String key) throws Exception {
//        System.out.println("Providers: ");
//        for (Provider provider : Security.getProviders()) {
//            System.out.println(provider.getName());
//        }
        byte[] result = encryptECB(data.getBytes(), key.getBytes());
        String resultStr = bytesToHex(result);
//        System.out.println("resultStr = "+ resultStr);
        return resultStr;
//        return bytesToHex(result);
    }
    public static byte[] encryptECB(byte[] data, byte[] key) throws Exception {


        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
        Security.addProvider(new BouncyCastleProvider());

        SecretKeySpec keySpec = new SecretKeySpec(key, "SM4");
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        return cipher.doFinal(data);
    }

    public static void main(String[] args) throws Exception {
        String plainText = "aaa111";
        byte[] key = "0000000000000000".getBytes(); // 密钥必须是 16 字节
        byte[] encryptedData = encryptECB(plainText.getBytes(), key);
        System.out.println("Encrypted: " + bytesToHex(encryptedData));
    }

    private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            hexChars[i * 2] = HEX_ARRAY[v >>> 4];
            hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
}
